<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" layout:decorate="~{layout.html}" th:with="currentPage=#{label.nexu.signature.process}">
	<body>		
		<div layout:fragment="content">
            <div class="progress" style="height: 35px">
                <div class="progress-bar progress-bar-striped  progress-bar-animated active" style="width: 0%" id="bar">
                    <span id="bar-text"></span>
                </div>
            </div>
            <div id="error" style="display: none" class="alert alert-danger text-break mt-3" role="danger">
                <strong id="errorText" th:text="#{label.error.occurred}"></strong>&nbsp;<span id="errorcontent"></span>
            </div>
		</div>
		<div layout:fragment="scripts">
			<script type="text/javascript" th:src="@{${nexuUrl}+'/nexu.js'}"></script>
		    <script type="text/javascript" th:inline="javascript">
		    /*<![CDATA[*/
		        
		            var tokenId;
		            var keyId;
		            
	                var csrf_token = $("meta[name='_csrf']").attr("content");
	                var csrf_header = $("meta[name='_csrf_header']").attr("content");
	                
	                var headers = new Array();
	                headers[csrf_header] = csrf_token; 
		            
		            window.onload = function() {
		                getCertificates();
		            };
		            
		            function getCertificates() {
		                updateProgressBar("Loading certificates...", "10%");
		                nexu_get_certificates(getDataToSign, error);
		            }
		            
		            function getDataToSign(certificateData) {
		                if(certificateData.response == null) {
		                    $('#bar').removeClass('bg-success progress-bar-striped progress-bar-animated active').addClass('bg-danger');
		                    $('#bar-text').html("Error");
		                    document.getElementById("errorcontent").innerHTML = "error while reading the Smart Card";
		                    $("#error").show();
		                } else {
		                    updateProgressBar("Computing the digest...", "25%");
		                    var signingCertificate = certificateData.response.certificate;
		                    var certificateChain = certificateData.response.certificateChain;
		                    var encryptionAlgorithm = certificateData.response.encryptionAlgorithm;
		                    tokenId = certificateData.response.tokenId.id;
		                    keyId = certificateData.response.keyId;
		                    var toSend = { signingCertificate: signingCertificate, certificateChain: certificateChain, encryptionAlgorithm: encryptionAlgorithm };
		                    call(/*[[${rootUrl+'/get-data-to-sign'}]]*/, "POST",  JSON.stringify(toSend), headers, sign, error);
		                }
		            }
		            
		            function sign(dataToSignResponse) {
		                if (dataToSignResponse == null) {
		                    $('#bar').removeClass('bg-success progress-bar-striped progress-bar-animated active').addClass('bg-danger');
		                    $('#bar-text').html("Error");
		                    $("#errorcontent").text("unable to compute the data to sign (see server logs)");
		                    $("#error").show();
		                } else {
		                    updateProgressBar("Signing the digest...", "50%");
		                    var digestAlgo = /*[[${digestAlgorithm.name}]]*/;
		                    nexu_sign_with_token_infos(tokenId, keyId, dataToSignResponse.dataToSign, digestAlgo, signDocument, error);
		                }
		            }
		            
		            function signDocument(signatureData) {
		                updateProgressBar("Signing the document...", "75%");
		                var signatureValue = signatureData.response.signatureValue;
		                var toSend = {signatureValue:signatureValue};
		                call(/*[[${rootUrl}+'/sign-document']]*/, "POST", JSON.stringify(toSend), headers, downloadSignedDocument, error);
		            }
		            
		            function downloadSignedDocument(signDocumentResponse) {
		                var url = signDocumentResponse.urlToDownload;
		                url = /*[[${rootUrl+'/download'}]]*/;
		                window.open(url, "_self");
		                updateProgressBar("Done !", "100%");
		                $('#bar').removeClass('progress-bar-striped active');
		                $('#bar').addClass('bg-success');
		            }
		            
		            function error(error) {
		                $('#bar').removeClass('bg-success progress-bar-striped progress-bar-animated active').addClass('bg-danger');
		                if (error != null) {
		                	var message = error.responseJSON;
		                	if (message == null) {
		                		message = error.responseText;
		                	}
		                	if (message.errorMessage != null) {
		                		message = message.errorMessage;
		                	}
		                	console.log(message);
		                    if (message != null){
		                        $("#errorcontent").html(message);
		                    }
		                }
		                $("#error").show();
		                $("#success").hide();
		            }
		            
		            function updateProgressBar(action, percent) {
		                $('#bar-text').html(action);
		                $('#bar').width(percent);
		            }
		            
		            function call(url, type, data, headers, success_callback, error_callback) {
		            	$.ajax({
		                      type: type,
		                      url: url,
		                      data: data,
		                      crossDomain: true, 
		                      contentType: "application/json; charset=utf-8",
		                      dataType: "json",
		                      headers : headers,
		                      success: function (result) {
		                          console.log(url + " : OK");
		                          success_callback.call(this, result);
		                      }
		                    }).fail(function (error, textStatus ) {
		                        console.log(url + " : NOT OK " + textStatus);
		                        error_callback.call(this, error);
		                    });
		            } 
		
		            /*]]>*/
		    </script>
		</div>
		
	</body>
</html>